package code14JDBC;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄衡熙
 * @version 1.0
 */
public class Test05_分页查询 {
    public static void main(String[] args) {
        List<User> list=selectPagAll(3,3);
        for(User user:list){
            System.out.println(user);
        }
    }
    public static List<User> selectPagAll(Integer pageNo, Integer pageSize) {
        List<User> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" select id, username, password, phone, address ")
                    .append(" from t_user ")
                    .append(" limit ?,? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setInt(1, (pageNo-1)*pageSize);
            ps.setInt(2, pageSize);
            rs = ps.executeQuery();
            while(rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                list.add(user);
            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            JDBCUtil.close(conn,ps,rs);
        }
    }
}
